package com.boot.bio;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * cmd
 * telnet localhost 6666
 * Ctrl+]
 * send aaa
 */
@Log
public class BIOServer {
    public static void main(String[] args) throws IOException {
//        创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

//        创建socket
        ServerSocket serverSocket = new ServerSocket(6666);
        while (true) {
            log.info(String.format("线程id：%s,线程名：%s", Thread.currentThread().getId(), Thread.currentThread().getName()));
//
            log.info("等待连接。。。");
            final Socket socket = serverSocket.accept();
            log.info("连接到一个客户端");

//            创建一个线程通讯
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    handle(socket);
                }
            });
        }


    }

    public static void handle(Socket socket) {
        try {
            log.info(String.format("线程id：%s,线程名：%s", Thread.currentThread().getId(), Thread.currentThread().getName()));
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true) {
                log.info(String.format("线程id：%s,线程名：%s", Thread.currentThread().getId(), Thread.currentThread().getName()));
                int read = inputStream.read(bytes);
                if (read == -1) {//已经读取完毕
                    break;
                } else {
                    log.info(new String(bytes, 0, read));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            log.info("关闭和client连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}